package ar.edu.utn.frsf.proyectofinal.sistemadecontrolmodbus.devicecontroller.test;

import static org.junit.Assert.assertTrue;

import java.io.IOException;
import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;

import net.wimpi.modbus.ModbusIOException;
import net.wimpi.modbus.io.ModbusTransport;
import net.wimpi.modbus.msg.ModbusMessage;
import net.wimpi.modbus.msg.ModbusRequest;
import net.wimpi.modbus.msg.ModbusResponse;

public class MocketActualizationModbusTransport implements ModbusTransport {

	private CyclicBarrier barrier;
	private ModbusRequest[] requests;
	private ModbusResponse[] responses;
	private int transactionreq;
	private int transactionres;
	
	@Override
	public void close() throws IOException {
		barrier = null; 
		requests = null;
		responses = null;
	}

	@Override
	public ModbusRequest readRequest() throws ModbusIOException {
		try {
			barrier.await();
		} catch (BrokenBarrierException e) {
			throw new ModbusIOException();
		}
		 catch (InterruptedException e) {
			throw new ModbusIOException();
		}
		requests[transactionreq].setTransactionID(transactionreq);
		return requests[transactionreq++];
	}

	@Override
	public ModbusResponse readResponse() throws ModbusIOException {
		throw new ModbusIOException();
	}

	@Override
	public void writeMessage(ModbusMessage msg) throws ModbusIOException {
		assertTrue(msg instanceof ModbusResponse);
		responses[transactionres++] = (ModbusResponse) msg;
	}

	/**
	 * @return the requests
	 */
	public ModbusRequest[] getRequests() {
		return requests;
	}

	/**
	 * @param modbusRequests the requests to set
	 */
	public void setRequests(ModbusRequest[] modbusRequests) {
		this.requests = modbusRequests;
	}

	/**
	 * @return the responses
	 */
	public ModbusResponse[] getResponses() {
		return responses;
	}

	/**
	 * @param responses the responses to set
	 */
	public void setResponses(ModbusResponse[] responses) {
		this.responses = responses;
	}

	/**
	 * @return the barrier
	 */
	public CyclicBarrier getBarrier() {
		return barrier;
	}

	/**
	 * @param barrier the barrier to set
	 */
	public void setBarrier(CyclicBarrier barrier) {
		this.barrier = barrier;
	}

	/**
	 * @return the transactionreq
	 */
	public int getTransactionreq() {
		return transactionreq;
	}

	/**
	 * @param transactionreq the transactionreq to set
	 */
	public void setTransactionreq(int transactionreq) {
		this.transactionreq = transactionreq;
	}

	/**
	 * @return the transactionres
	 */
	public int getTransactionres() {
		return transactionres;
	}

	/**
	 * @param transactionres the transactionres to set
	 */
	public void setTransactionres(int transactionres) {
		this.transactionres = transactionres;
	}


}
